import { mapGetters } from "vuex";
import {
  getFileExt,
  getUrlParam,
  isMobile,
  isNullObject,
} from "@/utils/helper";
import Api from "@/apiHttp";
export default {
  data() {
    return {
      Api: Api,
    };
  },
  computed: {
    ...mapGetters(["mailType"]),
  },
  methods: {
    /**
     * 封装路由
     * @param {path} 路由路径
     * @param {query} 路由跳转传参
     */
    RouterPush(path, query = {}) {
      this.$router
        .push({
          path: path,
          query: {
            ...query,
          },
        })
        .catch((err) => {
          console.warn("it is ok", err);
        });
    },
    /**
     * 保存用户信息到localstoreage
     */
    // saveTolocalStoreage() {
    //   console.warn("saveTolocalStoreage----调用");
    //   localStorage.setItem("_mailStore", JSON.stringify(this.$store.state));
    // },

    // 打开预览页面
    openPreview(url, config) {
      let appName = config && config.appName;
      // const appid =
      //   getUrlParam("appid") ||
      //   getUrlParam("client_id") ||
      //   getUrlParam("appId");
      if (isMobile() && window.qing.isSupportNativeJsBridge) {
        window.qing.call("gotoLightApp", {
          appName, // 顶部标题
          // appId: appid, // 携带ticket
          urlParam: `${url}`,
          orientation:'sensor',
          showMenu:false
        });
      } else {
        //web端测试跳转
        window.open(url);
      }
    },

    /**
     *
     *打开云之家 gotoLightApp
     *参数opinion: boolean 附件预览打开新页面相关 是否启用配置的baseUrl
     */
    openWebView(path, params = {}, opinion = true, url = "") {
      const ticket = getUrlParam("ticket");
      const appid =
        getUrlParam("appid") ||
        getUrlParam("client_id") ||
        getUrlParam("appId");
      const isParams = isNullObject(params);
      // this.saveTolocalStoreage();
      if (isMobile() && window.qing.isSupportNativeJsBridge) {
        console.warn("isMobile and support native js bridge")
        let urlParam = "";
        if (process.env.NODE_ENV === "development") {
          urlParam = `${
            opinion
              ? `${location.protocol}//${location.hostname}:${
                  process.env.VUE_APP_PORT
                }/oppo-mail/?appId=${appid}&ticket=1&isNavHidden=true#/${path}${
                  isParams
                    ? `?writeType=${encodeURIComponent(
                        params.writeType
                      )}&index=${params.index}&withAttach=${params.withAttach}`
                    : ""
                }`
              : `${url}`
          }`;
        } else {
          urlParam = `${
            opinion
              ? `${location.protocol}//${
                  location.hostname
                }/oppo-mail/?appId=${appid}&isNavHidden=true#/${path}${
                  isParams
                    ? `?writeType=${encodeURIComponent(
                        params.writeType
                      )}&index=${params.index}&withAttach=${params.withAttach}`
                    : ""
                }`
              : `${url}`
          }`;
        }
        console.warn("gotoLightApp")

        window.qing.call("gotoLightApp", {
          // appName: "详情",
          appId: appid,
          urlParam: urlParam,
        });
      } else {
        //web端测试跳转
        window.open(
          `${
            opinion
              ? `${location.protocol}//${location.hostname}:${
                  location.port
                }/oppo-mail/?ticket=${ticket}&appId=${appid}&isNavHidden=true#/${path}${
                  isParams
                    ? `?writeType=${encodeURIComponent(
                        params.writeType
                      )}&index=${params.index}&withAttach=${params.withAttach}`
                    : ""
                }`
              : `${url}`
          }`
        );
      }
    },

    // openWebView(path, params = {}) {
    //   const ticket = getUrlParam("ticket");
    //   const appid =
    //     getUrlParam("appid") ||
    //     getUrlParam("client_id") ||
    //     getUrlParam("appId");
    //   const isParams = isNullObject(params);
    //   this.saveTolocalStoreage();
    //   if (isMobile() && window.qing.isSupportNativeJsBridge) {
    //     window.qing.call("gotoLightApp", {
    //       // appName: "详情",
    //       appId: appid,
    //       urlParam: `${location.protocol}//${location.hostname
    //         }/oppo-mail/?appId=${appid}&isNavHidden=true#/${path}${isParams
    //           ? `?writeType=${encodeURIComponent(params.writeType)}&index=${params.index
    //           }&withAttach=${params.withAttach}`
    //           : ""
    //         }`,
    //     });
    //   } else {
    //     //web端测试跳转
    //     window.open(
    //       `${location.protocol}//${location.hostname}:${location.port
    //       }/oppo-mail/?ticket=${ticket}&appId=${appid}&isNavHidden=true#/${path}${isParams
    //         ? `?writeType=${encodeURIComponent(params.writeType)}&index=${params.index
    //         }&withAttach=${params.withAttach}`
    //         : ""
    //       }`
    //     );

    //     /*桌面端应用内 跳转*/
    //     // const query = isParams
    //     //   ? {
    //     //       writeType: params.writeType,
    //     //       index: params.index,
    //     //     }
    //     //   : {};
    //     // this.$router.push({ path: path, query: { ...query } });
    //   }
    // },

    /**
     * 选人桥
     * @param {}
     */
    // SelectPerson(options, isMulti = true) {
    //   return new Promise((reslove, reject) => {
    //     window.qing.call("selectPerson", {
    //       isMulti: isMulti,
    //       selected: options.map((p) => p.openId),
    //       extra: "email",
    //       success: function (res) {
    //         reslove(res);
    //       },
    //       error: (e) => {
    //         console.warn("error选人桥");
    //         console.warn(e);
    //         reject(e);
    //       },
    //     });
    //   });
    // },

    SelectPerson(options, isMulti = true) {
      return new Promise((reslove, reject) => {
        window.qing.call("selectPersons", {
          isMulti: isMulti,
          isShowMe:true,
          selected: options.map((p) => p.openId),
          // extra: "only",
          maxSelect: 500,
          needEmail: true,
          success: function (res) {
            reslove(res);
          },
          error: (e) => {
            console.warn("error选人桥");
            console.warn(e);
            reject(e);
          },
        });
      });
    },
    /**
     * 文件预览
     */
    ShowFile(file, url, serviceLocation) {
      const fileExt = getFileExt(file?.fileName);
      const params = {
        fileName: file?.fileName, //必选，string,文件名称
        fileExt: fileExt, //必选，string,文件后缀名
        // fileTime: '2014-11-28 13:23:54', //必选，string，文件时间
        fileSize: file?.fileSize, //必选，int，文件大小，单位：字节
        // bizkey: 'AVATAR',
        // fileId: file?.fileId || '',
        fileDownloadUrl: url || "",
      };
      if (serviceLocation !== "public") {
        //私有云 需要预览 传fileId
        params["fileId"] = file?.fileId;
      } else {
        //公有云 兼容
        params["fileTime"] = "2014-11-28 13:23:54"; //必选，string，文件时间
      }
      // console.error('showFile params:');
      // console.error(params)

      return new Promise((reslove, reject) => {
        window.qing.call("showFile", {
          ...params,
          success: function (res) {
            reslove(res);
          },
          error: (e) => {
            // console.error('showFile err:');
            // console.error(e)
            reject(e);
          },
        });
      });
    },
    /**
     * 原生导航控制
     */
    NavControl(title, popTitle, fn) {
      window.qing.call("setWebViewTitle", { title: title });
      window.qing.call("createPop", {
        popTitle: popTitle,
        popTitleCallBackId: "nav",
        success: function () {
          if (fn) {
            fn();
          } else {
            console.warn("无执行函数");
          }
        },
        error: function () {
          console.log("error");
        },
      });
    },
    /**
     * 邮件收藏/取消
     */
    // eslint-disable-next-line no-unused-vars
    // async collectMail(mail, type = 'single', isSelected) {
    //     const requestBody =
    //         type === 'single'
    //             ? mail.id || mail.uid
    //             : mail.map((m) => m.id).toString()
    //     try {
    //         console.error('test', !mail.collection)
    //         const res = !mail.collection
    //             ? await this.Api.collectMail(requestBody, type)
    //             : await this.Api.cancelCollect(requestBody, type)
    //         const { success } = res?.data
    //         if (success) {
    //             this.$toast.success(
    //                 !mail.collection ? '收藏成功' : '取消收藏成功'
    //             )
    //             if (type !== 'single') {
    //                 this.isSelected = false
    //             }
    //             mail.collection = !mail.collection
    //         } else {
    //             const msg = res?.data?.error_description || '系统错误'
    //             this.$toast.fail(msg)
    //         }
    //     } catch {
    //         console.error('收藏邮件失败')
    //     }
    // },

    /**
     * 删除数组中的某一个
     */
    delOneInArr(value, key, arr) {
      const index = arr.findIndex((i) => i[key] === value);
      if (index !== -1) {
        arr.splice(index, 1);
      }
    },
  },
};
